package rotation

import (
	"errors"
	"gin_demo/internal/consts"
	"gin_demo/internal/model"
	"gin_demo/utility"
	"time"

	"github.com/gin-gonic/gin"
)

func List(ctx *gin.Context) {
	list := []model.Rotation{}
	tx := consts.App.DB.Find(&list)
	if tx.Error != nil {
		err := errors.New("轮播图数据加载失败")
		consts.App.Log.Error(tx.Error.Error())
		utility.Fail(ctx, err.Error())
	} else {
		utility.Success(ctx, list)
	}

}

func Create(ctx *gin.Context, req RotationReq) {

	list := model.Rotation{
		PicUrl: req.PicUrl,
		Link:   req.Link,
		Sort:   req.Sort,
	}
	tx := consts.App.DB.Create(&list)
	if tx.Error != nil {
		err := errors.New("轮播图数据添加失败")
		consts.App.Log.Error(tx.Error.Error())
		utility.Fail(ctx, err.Error())
	} else {
		utility.Success(ctx, list)
	}

}

func Delete(ctx *gin.Context, req SoftDeleteReq) {
	tx := consts.App.DB.Model(&model.Rotation{}).Where("id=?", req.Id).Update("deleted_at", time.Now())
	if tx.Error != nil {
		err := errors.New("轮播图删除失败")
		consts.App.Log.Error(tx.Error.Error())
		utility.Fail(ctx, err.Error())
	} else {
		utility.Success(ctx, "轮播图删除成功")
	}

}

func Update(ctx *gin.Context, req UpdateRotationReq) {
	list := model.Rotation{
		PicUrl: req.PicUrl,
		Link:   req.Link,
		Sort:   req.Sort,
	}
	tx := consts.App.DB.Model(&model.Rotation{}).Where("id=?", req.Id).Updates(&list)
	if tx.Error != nil {
		err := errors.New("轮播图更新失败")
		consts.App.Log.Error(tx.Error.Error())
		utility.Fail(ctx, err.Error())
	} else {
		utility.Success(ctx, list)
	}

}
